<template>
    <div id="create-edit-container">
        <!-- use the modal component, pass in the prop -->
        <Modal v-model="stateManager.editDialogVisible"
               :title="modalTitle"
               width="60%"
               @on-cancel="closeDialog"
               :styles="{top: '20px'}"
               :mask-closable="false">

            <Row type="flex">
                <i-col span="20">
                    <i-input type="text" v-model="teacherMobile" placeholder="请输入教师的电话号码"></i-input>
                </i-col>
                <i-col span="3" offset="1">
                    <i-button type="ghost" icon="ios-search" @click="searchTeacher">查询</i-button>
                </i-col>
            </Row>

            <i-form ref="model" :model="model" :rules="ruleValidate">
                <Row type="flex" v-if="model.teacher_user_id">
                    <i-col span="8">姓名：{{teacher.name}}</i-col>
                    <i-col span="8">学校：{{teacher.school_cn}}</i-col>
                    <i-col span="8">手机：{{teacher.mobile}}</i-col>
                    <i-col span="24">
                        <Form-item label="排序" prop="sort">
                            <Input-number :min="1" :max="1000" v-model="model.sort" style="width: 100%"></Input-number>
                        </Form-item>
                    </i-col>
                    <i-col span="24">
                        <Form-item label="院校介绍信息">
                            <quill-editor v-model="model.school_info" style="margin-top: 38px"></quill-editor>
                        </Form-item>
                    </i-col>
                </Row>
            </i-form>

            <i-form ref="imgModel" :model="imgModel" :rules="imgRules" >
                <Row type="flex" v-if="model.id !== 0">
                    <i-col span="24">
                        <template v-for="item in imgList">
                            <i-col span="6" style="padding: 10px">
                                <div class="demo-upload-list">
                                    <img  :src="imgBaseUrl + '/' + item.path" alt="" style="max-width: 100%; max-height: 100px;">
                                    <div class="demo-upload-list-cover">
                                        <h5><a :href="item.pivot.point_url" target="_blank">{{item.pivot.title}}</a></h5>
                                        <i-button type="text" @click="deleteFile(item.id)" style="margin-top: 25px">
                                            <Icon type="ios-trash" ></Icon>
                                        </i-button>
                                    </div>
                                </div>
                            </i-col>
                        </template>
                    </i-col>
                    <i-col span="11">
                        <Form-item label="图片标题" prop="title">
                            <i-input type="text" v-model="imgModel.title" placeholder="请输入图片标题"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="图片指向URL" prop="point_url">
                            <i-input type="text" v-model="imgModel.point_url" placeholder="请输入图片指向URL"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="24">
                        <Form-item label="上传图片">
                            <Upload type="drag" :action="'api/famous-teacher/file-upload/' + model.id"
                                    ref="upload"
                                    :headers="uploadHeaders"
                                    :on-success="uploadSuccessCallback"
                                    :on-error="uploadFailedCallback"
                                    :max-size="10240"
                                    :data="imgModel"
                                    :before-upload="checkUpload"
                                    :format="['jpg', 'jpeg', 'png']"
                                    style="margin-top: 40px">
                                <div style="padding: 20px 0" >
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <i-input type="text" v-model="model.file_id" hidden></i-input>
                        </Form-item>
                    </i-col>
                </Row>
            </i-form>


            <template slot="footer">
                <Row type="flex">
                    <i-col span="24">
                        <div class="pull-right">
                            <i-button type="ghost" @click="closeDialog">取消</i-button>
                            <i-button type="primary" @click="saveModel" :loading="isLoading">确定</i-button>
                        </div>
                    </i-col>
                </Row>
            </template>

        </Modal>

    </div>


</template>

<script>
    import QuillEditor from "vue-quill-editor/src/editor";
    export default {
        components: {QuillEditor},
        props: {
            stateManager: {
                type: Object
            }
        },
        data: function () {
            return {
                model: this.$modelDataSource({
                    url: 'api/famous-teacher',
                    dataKey: 'model',
                    attributes: {
                        id: 0,
                        teacher_user_id: '',
                        sort: 1,
                        school_info: ''
                    }
                }),
                teacher: {},
                teacherMobile: '',
                imgList: {},
                imgModel: {
                    point_url: '',
                    title: ''
                },
                uploadHeaders: window.uploadHeaders,
                isLoading: false,
                ruleValidate: {
                    sort: [
                        { required: true, type: 'number', message: '排序为正整数，请输入有效的数字', trigger: 'blur' }
                    ]
                },
                imgRules: {
                    title: [
                        { required: true, message: '图片标题不能为空', trigger: 'blur' }
                    ],
                    point_url: [
                        { required: true, message: '图片指向URL不能为空', trigger: 'blur' }
                    ]
                }
            };
        },
        created: function () {
        },
        methods: {
            checkUpload: function (file) {
                console.log(file);
                return new Promise((resolve, reject) => {
                    this.$refs.imgModel.validate((valid) => {
                        if (valid){
                            console.log('验证通过');
                            resolve(true);
                        }else{
                            console.log('验证失败');
                            reject('请认真填写图片标题和指向URL');
                        }
                    });
                });
            },
            searchTeacher: function () {
                let self = this;
                if (self.teacherMobile){
                    axios.get('api/famous-teacher/search-teacher/' + this.teacherMobile).then(function (response) {
                        self.teacher = response.data;
                        self.model.teacher_user_id = response.data.user_id;
                    }).catch(function (error) {
                        console.log(error.response.data);
                        this.$Notice.error({title: '错误！', desc: error.response.data.search_failed});
                    })
                }else{
                    this.$Notice.error({title: '错误！', desc: '请输入正确的手机号！'});
                }
            },
            getImgList: function () {
                let self = this;
                axios.get('api/famous-teacher/img-list/' + self.model.id).then(function (response) {
                    self.imgList = response.data;
                }).catch(function (error) {
                    console.log(error);
                })
            },
            closeDialog: function () {
                this.stateManager.editDialogVisible = false;
                this.model.reset();
                this.$refs['model'].resetFields();
                this.teacherMobile = '';
                this.stateManager.editModelId = 0;
            },
            uploadSuccessCallback: function (response, file) {
                //上传成功回调
                console.log(file);
                console.log(response);
                if (response.status == 'success'){
                    this.getImgList();
                }
            },
            uploadFailedCallback: function (error, file) {
                //上传失败回调
                console.log(error);
                console.log(file);
            },
            deleteFile: function (fileId) {
                let self = this;
                self.$Modal.confirm({
                    title: '确定删除吗？',
                    content: '删除后无法恢复',
                    loading: true,
                    onOk: function () {
                        axios.get('api/famous-teacher/delete-file/' + self.model.id + '/' + fileId).then(function (response) {
                            if (response.data.state === 'success'){
                                self.$Modal.remove();
                                self.getImgList();
                                self.$Notice.success({title: '删除成功', desc: '已删除该图片'});
                            }else{
                                console.log(response.data);
                            }
                        }).catch(function (error) {
                            console.log(error);
                        })
                    },
                    onCancel: function () {
                        console.log('取消删除');
                    }
                });
            },
            saveModel: function () {
                let self = this;
                self.$refs['model'].validate((valid) => {
                    if (valid){
                        console.log('表单验证通过');
                        self.isLoading = true;
                        self.model.save(function () {
                            self.isLoading = false;
                            self.$Notice.success({
                                title: '保存成功',
                                desc: self.teacher.name
                            });
                            self.stateManager.refreshList = true;
                        }, function () {
                            console.log(self.model.errors);
                            self.isLoading = false;
                            _.forOwn(self.model.errors, function (value, key) {
                                if (value){
                                    self.$Notice.error({
                                        title: '保存失败',
                                        desc: value
                                    });
                                }
                            });
                        });
                    }else{
                        console.log('表单验证失败');
                    }
                })
            }
        },
        computed: {
            modalTitle: function () {
                if (this.model.id === 0){
                    return '添加名师';
                }else{
                    return '修改名师';
                }
            },
            imgBaseUrl(){
                return window.Laravel.imgBaseUrl;
            }
        },
        watch: {
            'stateManager.editModelId': function (newValue) {
                let self = this;
                this.model.fetch(newValue, function () {
                    self.stateManager.buttonLoading = false;
                    self.stateManager.editDialogVisible = true;
                    self.teacher = self.model.teacher;
                    self.imgList = self.model.file;
                    self.$refs['upload'].clearFiles();
                }, function () {
                    self.stateManager.buttonLoading = false;
                    self.$Notice.error({
                        title: '数据加载超时',
                        desc: '请尝试刷新页面，并仔细检查网络链接状况或联系技术人员！'
                    });
                });
            }
        }
    }
</script>

<style>
    .demo-upload-list{
        display: inline-block;
        width: 100%;
        text-align: center;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        padding: 10px;
    }
    /*.demo-upload-list img{*/
        /*width: 100%;*/
        /*height: 100%;*/
    /*}*/
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>